/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// default
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// xử lý upload
import java.io.File;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

// xử lý xml
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

// xử lý csdl
import java.sql.*;

/**
 *
 * @author Tan Thanh
 */
@WebServlet(name = "cauhoi_import", urlPatterns = {"/cauhoi_import"})
public class cauhoi_import extends HttpServlet {

	/**
	 * Processes requests for both HTTP
	 * <code>GET</code> and
	 * <code>POST</code> methods.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Thi trắc nghiệm online</title>");
		out.println("</head>");
		out.println("<body>");
		try {
			// Check that we have a file upload request
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) {
				throw new ServletException("Dùng sai dạng form");
			}

			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//factory.setSizeThreshold(1024); // yourMaxMemorySize
			//factory.setRepository(new java.io.File("C:/tempDir")); // yourTempDirectory

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			//upload.setSizeMax(2048); // yourMaxRequestSize

			// Parse the request
			List items = upload.parseRequest(request);
			ListIterator iterator = items.listIterator();
			while (iterator.hasNext()) // duyệt các param được upload
			{
				FileItem item = (FileItem) iterator.next();
				if (item.isFormField()) // param dạng input
				{
					String name = item.getFieldName();
					String value = item.getString("utf-8");
				} else // param dạng file
				{
					String fileName = item.getName(); // tên file
					String realPath = getServletContext().getRealPath(""); // lấy Root path trên server
					String filePath = realPath + "/files/" + fileName; // đường dẫn lưu file
					File file = new File(filePath); // tạo file theo đường dẫn
					item.write(file); // ghi file

					out.println("<h1>File upload successfully !</h1>");
					out.println("<h3><i>Đường dẫn file đã upload : " + "/files/" + fileName + "</i></h3>");

					/******************************************************/
					/************ ĐỌC FILE XML VÀ GHI VÀO CSDL ************/
					/******************************************************/
					Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(getServletContext().getRealPath("/") + "web.xml"));
					doc.getDocumentElement().normalize();
					String dbhost = doc.getElementsByTagName("host").item(0).getTextContent();
					String dbport = doc.getElementsByTagName("port").item(0).getTextContent();
					String dbuser = doc.getElementsByTagName("user").item(0).getTextContent();
					String dbpass = doc.getElementsByTagName("pass").item(0).getTextContent();
					String dbname = doc.getElementsByTagName("database").item(0).getTextContent();
					String dbconnString = "jdbc:mysql://" + dbhost + ":" + dbport + "/" + dbname + "?setUnicode=true&characterEncoding=UTF-8";
					Class.forName("com.mysql.jdbc.Driver").newInstance();
					Connection dbconn = DriverManager.getConnection(dbconnString, dbuser, dbpass);
					CallableStatement query = dbconn.prepareCall("insert into cauhoi (noidung, luachon1, luachon2, luachon3, luachon4, dapan, dokho) values (?, ?, ?, ?, ?, ?, ?)");

					File fXmlFile = new File(filePath);
					DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
					DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
					Document doc2 = dBuilder.parse(fXmlFile);
					doc2.getDocumentElement().normalize();
					//out.println("Root element : " + doc.getDocumentElement().getNodeName());

					NodeList cauhoiList = doc2.getElementsByTagName("Cauhoi");
					for (int i = 0; i < cauhoiList.getLength(); i++) {
						Node cauhoiNode = cauhoiList.item(i);
						if (cauhoiNode.getNodeType() == Node.ELEMENT_NODE) {
							Element cauhoiElement = (Element) cauhoiNode;
							NodeList noidung, luachon, dapan, dokho;
							noidung = cauhoiElement.getElementsByTagName("Noidung");
							luachon = cauhoiElement.getElementsByTagName("Luachon");
							dapan = cauhoiElement.getElementsByTagName("Dapan");
							dokho = cauhoiElement.getElementsByTagName("Dokho");
							query.setString(1, noidung.item(0).getTextContent());
							query.setString(2, luachon.item(0).getTextContent());
							query.setString(3, luachon.item(1).getTextContent());
							query.setString(4, luachon.item(2).getTextContent());
							query.setString(5, luachon.item(3).getTextContent());
							query.setInt(6, Integer.parseInt(dapan.item(0).getTextContent()));
							query.setInt(7, Integer.parseInt(dokho.item(0).getTextContent()));
							query.executeUpdate();
						}
					}

					dbconn.close();
					out.println("<h1>File import successfully !</h1>");
					out.println("<h3><i>Số lượng câu hỏi đã import : " + cauhoiList.getLength() + "</i></h3>");
				}
			}
		} catch (Exception e) {
			out.println("Exception : " + e.getMessage());
		} finally {
			out.println("<br/><a href='cauhoi.jsp'>Nhấn vào đây để trở lại</a><br/>Hoặc trình duyệt sẽ tự động chuyển sau");
			out.println("<div id='javascript_countdown_time'></div>");
			out.println("<script type='text/javascript' src='js/countdown.js'></script>");
			out.println("<script type='text/javascript'> "
					+ "timeleft_function = function() { window.location = 'cauhoi.jsp'; }; "
					+ "javascript_countdown.init(15, 'javascript_countdown_time'); "
					+ "</script>");
			out.println("</body>");
			out.println("</html>");
			out.close();
		}
	}

	// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	/**
	 * Handles the HTTP
	 * <code>GET</code> method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP
	 * <code>POST</code> method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 *
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
